/**
 * 性能监控工具
 * 用于监控页面性能指标
 */

/**
 * 获取性能指标
 */
export function getPerformanceMetrics() {
  if (!window.performance || !window.performance.timing) {
    console.warn('Performance API not supported')
    return null
  }

  const timing = window.performance.timing
  const navigation = window.performance.navigation

  return {
    // 页面加载总时间
    loadTime: timing.loadEventEnd - timing.navigationStart,
    
    // DNS 查询时间
    dnsTime: timing.domainLookupEnd - timing.domainLookupStart,
    
    // TCP 连接时间
    tcpTime: timing.connectEnd - timing.connectStart,
    
    // 请求时间
    requestTime: timing.responseEnd - timing.requestStart,
    
    // 响应时间
    responseTime: timing.responseEnd - timing.responseStart,
    
    // DOM 解析时间
    domParseTime: timing.domInteractive - timing.domLoading,
    
    // DOM 内容加载完成时间
    domContentLoadedTime: timing.domContentLoadedEventEnd - timing.navigationStart,
    
    // 首次渲染时间
    firstPaintTime: timing.responseEnd - timing.fetchStart,
    
    // 白屏时间
    whiteScreenTime: timing.responseStart - timing.navigationStart,
    
    // 页面类型
    navigationType: navigation.type,
    
    // 重定向次数
    redirectCount: navigation.redirectCount
  }
}

/**
 * 监听页面加载完成
 */
export function onPageLoad(callback) {
  if (document.readyState === 'complete') {
    callback()
  } else {
    window.addEventListener('load', callback)
  }
}

/**
 * 获取资源加载性能
 */
export function getResourceMetrics() {
  if (!window.performance || !window.performance.getEntriesByType) {
    return []
  }

  const resources = window.performance.getEntriesByType('resource')
  
  return resources.map(resource => ({
    name: resource.name,
    type: resource.initiatorType,
    duration: resource.duration,
    size: resource.transferSize || 0,
    startTime: resource.startTime
  }))
}

/**
 * 监控长任务
 */
export function monitorLongTasks(callback) {
  if (!window.PerformanceObserver) {
    console.warn('PerformanceObserver not supported')
    return
  }

  try {
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        callback({
          duration: entry.duration,
          startTime: entry.startTime,
          name: entry.name
        })
      }
    })

    observer.observe({ entryTypes: ['longtask'] })
    
    return () => observer.disconnect()
  } catch (e) {
    console.warn('Long task monitoring not supported')
  }
}

/**
 * 监控首次内容绘制 (FCP)
 */
export function monitorFCP(callback) {
  if (!window.PerformanceObserver) {
    return
  }

  try {
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.name === 'first-contentful-paint') {
          callback(entry.startTime)
          observer.disconnect()
        }
      }
    })

    observer.observe({ entryTypes: ['paint'] })
  } catch (e) {
    console.warn('FCP monitoring not supported')
  }
}

/**
 * 监控最大内容绘制 (LCP)
 */
export function monitorLCP(callback) {
  if (!window.PerformanceObserver) {
    return
  }

  try {
    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries()
      const lastEntry = entries[entries.length - 1]
      callback(lastEntry.renderTime || lastEntry.loadTime)
    })

    observer.observe({ entryTypes: ['largest-contentful-paint'] })
    
    return () => observer.disconnect()
  } catch (e) {
    console.warn('LCP monitoring not supported')
  }
}

/**
 * 监控首次输入延迟 (FID)
 */
export function monitorFID(callback) {
  if (!window.PerformanceObserver) {
    return
  }

  try {
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        callback(entry.processingStart - entry.startTime)
      }
    })

    observer.observe({ entryTypes: ['first-input'] })
    
    return () => observer.disconnect()
  } catch (e) {
    console.warn('FID monitoring not supported')
  }
}

/**
 * 监控累积布局偏移 (CLS)
 */
export function monitorCLS(callback) {
  if (!window.PerformanceObserver) {
    return
  }

  let clsValue = 0

  try {
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (!entry.hadRecentInput) {
          clsValue += entry.value
          callback(clsValue)
        }
      }
    })

    observer.observe({ entryTypes: ['layout-shift'] })
    
    return () => observer.disconnect()
  } catch (e) {
    console.warn('CLS monitoring not supported')
  }
}

/**
 * 打印性能报告
 */
export function printPerformanceReport() {
  onPageLoad(() => {
    const metrics = getPerformanceMetrics()
    
    if (!metrics) return

    console.group('📊 Performance Metrics')
    console.log('⏱️  Page Load Time:', metrics.loadTime.toFixed(2), 'ms')
    console.log('🌐 DNS Time:', metrics.dnsTime.toFixed(2), 'ms')
    console.log('🔌 TCP Time:', metrics.tcpTime.toFixed(2), 'ms')
    console.log('📡 Request Time:', metrics.requestTime.toFixed(2), 'ms')
    console.log('📦 Response Time:', metrics.responseTime.toFixed(2), 'ms')
    console.log('🏗️  DOM Parse Time:', metrics.domParseTime.toFixed(2), 'ms')
    console.log('📄 DOM Content Loaded:', metrics.domContentLoadedTime.toFixed(2), 'ms')
    console.log('🎨 First Paint Time:', metrics.firstPaintTime.toFixed(2), 'ms')
    console.log('⚪ White Screen Time:', metrics.whiteScreenTime.toFixed(2), 'ms')
    console.groupEnd()

    // 监控 Core Web Vitals
    monitorFCP((fcp) => {
      console.log('🎨 FCP (First Contentful Paint):', fcp.toFixed(2), 'ms')
    })

    monitorLCP((lcp) => {
      console.log('🖼️  LCP (Largest Contentful Paint):', lcp.toFixed(2), 'ms')
    })

    monitorFID((fid) => {
      console.log('⚡ FID (First Input Delay):', fid.toFixed(2), 'ms')
    })

    monitorCLS((cls) => {
      console.log('📐 CLS (Cumulative Layout Shift):', cls.toFixed(4))
    })
  })
}

/**
 * 检测用户偏好的动画设置
 */
export function prefersReducedMotion() {
  return window.matchMedia('(prefers-reduced-motion: reduce)').matches
}

/**
 * 检测设备性能
 */
export function getDevicePerformance() {
  const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection
  
  return {
    // CPU 核心数
    cores: navigator.hardwareConcurrency || 4,
    
    // 内存大小 (GB)
    memory: navigator.deviceMemory || 'unknown',
    
    // 网络类型
    effectiveType: connection?.effectiveType || 'unknown',
    
    // 是否省流量模式
    saveData: connection?.saveData || false
  }
}

